package com.dylan.历史.多线程.并发编程的艺术.编程基础.自制线程池;

import com.dylan.历史.util.SleepUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;

/**
 * Created by Dylan on 2018/7/17.
 */
public class 测试线程池 {

    public static void main(String[] args) {
        // 创建一个线程池
        ThreadPool<Compute> threadPool = new DefaultThreadPool<>(8);
        // 向线程池添加任务
        for (int i=0; i<100; i++) {
            threadPool.execute(new Compute(i));
        }
        SleepUtils.seconds(1);
        // 减少线程
        threadPool.removeWorker(5);
        System.out.println(DateFormatUtils.format(new Date(), "[yyyy-MM-dd HH:mm:ss.SSS ") + Thread.currentThread().getName() + "] - 修改线程数");
        SleepUtils.seconds(2);
        // 增加线程
        threadPool.addWorkers(10);
        System.out.println(DateFormatUtils.format(new Date(), "[yyyy-MM-dd HH:mm:ss.SSS ") + Thread.currentThread().getName() + "] - 修改线程数");
    }

    // 模拟计算任务
    static class Compute implements Runnable {

        private int jobNo;

        public Compute(int jobNo) {
            this.jobNo = jobNo;
        }

        @Override
        public void run() {
            System.out.println(DateFormatUtils.format(new Date(), "[yyyy-MM-dd HH:mm:ss.SSS ") + Thread.currentThread().getName() + "] - 任务" + jobNo + "开始计算");
            SleepUtils.milliseconds(RandomUtils.nextInt(0, 1000));
            System.out.println(DateFormatUtils.format(new Date(), "[yyyy-MM-dd HH:mm:ss.SSS ") + Thread.currentThread().getName() + "] - 任务" + jobNo + "结束计算");
        }
    }
}
